package com.guochenglang.www.service.impl;

import com.guochenglang.www.dao.TracesDao;
import com.guochenglang.www.pojo.Traces;
import com.guochenglang.www.service.TracesService;
import com.guochenglang.www.service.anotate.Affair;
import com.guochenglang.www.util.MyDependency;

import java.sql.SQLException;
import java.util.ArrayList;

/**
 * 浏览记录业务
 *
 * @author GuoChenglang
 */
public class TracesServiceImpl implements TracesService {
    private static final TracesDao TRACES_DAO = MyDependency.returnObject(TracesDao.class);

    /**
     * 获得用户的浏览记录
     *
     * @param userId 用户id
     * @return 用户的浏览记录
     */
    @Override
    public ArrayList<Traces> selectTraces(Integer userId) throws SQLException, InterruptedException, IllegalAccessException, InstantiationException {
        //获得用户浏览记录
        return TRACES_DAO.tracesSelect(new Traces(null, null, userId));
    }

    /**
     * 添加浏览记录
     *
     * @param traces 浏览记录的信息
     * @return 主键
     */
    @Affair
    @Override
    public int insertTraces(Traces traces) throws SQLException, InterruptedException, IllegalAccessException, InstantiationException {
        //搜索是否已经在浏览记录中
        ArrayList<Traces> traces1 = TRACES_DAO.tracesSelect(traces);
        System.out.println(traces1);
        if (!traces1.isEmpty()) {
            //若存在先删除在添加，变成最新的浏览记录
            TRACES_DAO.deleteTraces(traces);
        }
        System.out.println(traces);
        return (int) TRACES_DAO.insertTraces(traces);
    }

    /**
     * 删除浏览记录
     *
     * @param traceId 浏览记录id
     * @return 删除行数
     */
    @Affair
    @Override
    public int deleteATraces(Integer traceId) throws SQLException, InterruptedException, IllegalAccessException, InstantiationException {
        Traces trace = new Traces();
        trace.setId(traceId);
        return TRACES_DAO.deleteTraces(trace);
    }

    /**
     * 删除全部浏览记录
     *
     * @param userId 用户id
     * @return 删除行数
     */
    @Affair
    @Override
    public int deleteAll(Integer userId) throws SQLException, InterruptedException, IllegalAccessException, InstantiationException {
        Traces trace = new Traces();
        trace.setUserId(userId);
        return TRACES_DAO.deleteTraces(trace);
    }
}
